/**
 * 游戏场景
 */
class GameScene extends eui.UILayer {
    public start():void {};
    public end():void {};
}

/**玩家 */
class User extends Object {
    public goldCount:number = 0;
}

/**
 * 游戏控制api
 */
class myGame {
    private static machine:Machine;
    /**松鼠进场计时器 */
    private static dollsTimer:egret.Timer;

    /**
     * 创建抓松鼠机
     */
    public static createMachine(width:number, height:number):Machine {
        if(!this.machine) {
            this.machine = new Machine(width, height);
        }
        return this.machine;
    }
    public static getMachine() {
        return this.machine;
    }
    /**
     * 切换金币模式:x5\x10\x20
     */
    public static setModel(goldModel:number) {
        if (!this.machine) return void(0);
        
        this.machine.goldModel = goldModel;

        //启动骨骼动画播放
        this.machine.play("begin");
        
        //计时器，松鼠定时出场        
        if (!this.dollsTimer) {
            this.dollsTimer = new egret.Timer(800, -1);
            this.dollsTimer.addEventListener(egret.TimerEvent.TIMER, this.addDoll, this.machine);
        } else {
            this.dollsTimer.reset(); //计时器重置
            this.machine.getDollsContainer().removeChildren(); //移除所有松鼠
        }
        egret.setTimeout( function( arg ){
            this.dollsTimer.start(); //延迟1秒开始计时
        }, this, 1000);
    }
    /**
     * 游戏开始
     */
    public static startGame():void {
        if (!this.machine) return void(0);
                    
        this.machine.addEventListener("btn-goldx5-press", function() {
            myGame.setModel(5);
        }, this.machine);
        this.machine.addEventListener("btn-goldx10-press", function() {
            myGame.setModel(10);
        }, this.machine);
        this.machine.addEventListener("btn-goldx20-press", function() {
            myGame.setModel(20);
        }, this.machine);
        /**抓取动作碰撞检测，判断是否抓取到松鼠 */
        this.machine.addEventListener("clutch", function(){
            let numChildren = this.dollsContainer.numChildren || 0;
            let hitTestArea = this.hitTestArea;
            for(var i=0; i<numChildren; i++) {
                let doll = this.dollsContainer.getChildAt(i),
                    armatureDisplay,point,x,y;
                if (doll) {
                    armatureDisplay = doll.armatureDisplay;
                    if (armatureDisplay) {
                        point = armatureDisplay.getChildAt(0).localToGlobal();
                        x = point.x + armatureDisplay.width/2;
                        y = point.y + armatureDisplay.height/2;
                        if (hitTestArea.hitTestPoint(x,y)) {
                            let gift = armatureDisplay.getChildAt(0);
                            armatureDisplay.removeChild(gift);
                            this.clutched(doll);
                            break;
                        }
                    }
                }

            }

        }, this.machine)

        this.machine.play("btn-goldx5-press");
    }

    /**
     * 结束游戏
     */
    public static destoryGame():void {
        if (this.machine) {
            this.machine.destory();
            this.machine = null;
        }
    }

    /**
     * 单个松鼠进场
     */
    public static addDoll():void {
        let doll = new Doll(myGame.machine.goldModel);
        myGame.machine.getDollsContainer().addChild(doll);
        doll.go();
    }
}


/**
 * 抓松鼠机
 */
class Machine extends egret.DisplayObjectContainer {
    private static STATUS = {
        create:0,
        ready: 1,
        clutching: 2,
        disable: -1
    }

    public constructor(width, height) {
        super();
        this.name = "Machine";
        this.create();
    }
    /**金币模式：x5,x10,x20 */
    public goldModel:number;
    /**舞台的状态标识 */
    private status;
    /**抓到的松鼠 */
    private dollClutched;
    /**舞台的动作列表 */
    private actionArray;
    /**舞台的实体数据 */
    private armature;
    private btnArmature;
    /**舞台的可视对象 */
    private armatureDisplay;
    private btnArmatureDisplay;
    /**松鼠过场区域 */
    private dollsContainer:egret.DisplayObjectContainer;
    public getDollsContainer() { return this.dollsContainer; };
    /**抓取松鼠碰撞检测区域 */
    private hitTestArea;
    /**创建舞台骨骼模型 */
    private create():void {
        this.status = Machine.STATUS.create;
        this.actionArray = ["begin", "btn-go-press", "btn-goldx5-press", "btn-goldx10-press","btn-goldx20-press", "clutch", "clutch_back"];
        this.x = 0;
        this.y = 0;
        //读取机器的骨骼数据,并创建实例显示到舞台
        let factory = new dragonBones.EgretFactory();
        factory.addSkeletonData(dragonBones.DataParser.parseDragonBonesData(RES.getRes("machine_ske_json")));
        factory.addTextureAtlas(new dragonBones.EgretTextureAtlas(RES.getRes("machine_tex_png"), RES.getRes("machine_tex_json")));
        this.armature = factory.buildArmature("machine");
        this.armatureDisplay = this.armature.getDisplay();
        this.addChild(this.armatureDisplay);
        this.armatureDisplay.name = "MacArmatureDisplay";
        this.armatureDisplay.scaleX = 1; //设置X轴缩放比例
        this.armatureDisplay.scaleY = 1; //设置Y轴缩放比例
        this.armatureDisplay.x = 0;
        this.armatureDisplay.y = 0;
        //读取机器的骨骼数据,并创建实例显示到舞台
        let factory2 = new dragonBones.EgretFactory();
        factory2.addSkeletonData(dragonBones.DataParser.parseDragonBonesData(RES.getRes("btnGroup_ske_json")));
        factory2.addTextureAtlas(new dragonBones.EgretTextureAtlas(RES.getRes("btnGroup_tex_png"), RES.getRes("btnGroup_tex_json")));
        this.btnArmature = factory2.buildArmature("btnGroup");
        this.btnArmatureDisplay = this.btnArmature.getDisplay();
        this.addChild(this.btnArmatureDisplay);
        this.btnArmatureDisplay.name = "BtnArmatureDisplay"
        this.btnArmatureDisplay.scaleX = 1; //设置X轴缩放比例
        this.btnArmatureDisplay.scaleY = 1; //设置Y轴缩放比例
        this.btnArmatureDisplay.x = 0;
        this.btnArmatureDisplay.y = 0;


        this.addEventListener(egret.Event.ENTER_FRAME, this.onEnterFrame, this);
        dragonBones.WorldClock.clock.add(this.armature);
        dragonBones.WorldClock.clock.add(this.btnArmature);
        /**绑定关键帧监听事件 */
        this.armature.addEventListener(dragonBones.FrameEvent.ANIMATION_FRAME_EVENT, this.onFrameEvent, this);
        this.btnArmature.addEventListener(dragonBones.FrameEvent.ANIMATION_FRAME_EVENT, this.onFrameEvent, this);
    
        /**添加按钮点击事件 */
        let goBtn = this.armatureDisplay.getChildAt(6);
        let gx5Btn = this.btnArmatureDisplay.getChildAt(0);
        let gx10Btn = this.btnArmatureDisplay.getChildAt(1);
        let gx20Btn = this.btnArmatureDisplay.getChildAt(2);
        goBtn.touchEnabled = true
        gx5Btn.touchEnabled = true
        gx10Btn.touchEnabled = true
        gx20Btn.touchEnabled = true
        goBtn.addEventListener(egret.TouchEvent.TOUCH_TAP, function() {
            if (this.status == Machine.STATUS.ready) {
                this.play("btn-go-press");
            }
        }, this);
        gx5Btn.addEventListener(egret.TouchEvent.TOUCH_TAP, function() {
            if (this.status == Machine.STATUS.ready && this.goldModel != 5) {
                this.play("btn-goldx5-press");
            }
        }, this);
        gx10Btn.addEventListener(egret.TouchEvent.TOUCH_TAP, function() {
            if (this.status == Machine.STATUS.ready && this.goldModel != 10) {
                this.play("btn-goldx10-press");
            }
        }, this);
        gx20Btn.addEventListener(egret.TouchEvent.TOUCH_TAP, function() {
            if (this.status == Machine.STATUS.ready && this.goldModel != 20) {
                this.play("btn-goldx20-press");
            }
        }, this);

        /**松鼠过场区域 */
        this.dollsContainer = new egret.DisplayObjectContainer();
        this.dollsContainer.name = "DollsContainer";
        this.dollsContainer.width = 600;
        this.dollsContainer.height = 300;
        this.dollsContainer.x = 58;
        this.dollsContainer.y = 550;
        this.dollsContainer.mask = new egret.Rectangle(0,0,600,300);
        this.addChild(this.dollsContainer);
        /**添加碰撞检测区域 */
        this.hitTestArea = new egret.Shape();
        this.hitTestArea.name = "HitTestArea";
        this.hitTestArea.graphics.drawRect( 0,0,80,300);
        this.hitTestArea.width = 80;
        this.hitTestArea.height = 300;
        this.hitTestArea.x = 320;
        this.hitTestArea.y = 550;
        this.addChild(this.hitTestArea);
    }
    /**动画播放 */
    private onEnterFrame(evt:egret.Event):void {
        dragonBones.WorldClock.clock.advanceTime(  -1 );
    }
    /**播放指定动作 */
    public play(action:string,...args:any[]):void {
        if (["btn-goldx5-press","btn-goldx10-press","btn-goldx20-press"].indexOf(action)>=0) {
            this.btnArmature.animation.play(action,1);
        } else {
            this.armature.animation.play(action,1);
        }
    }
    /**动画关键帧监听 */
    private onFrameEvent(evt:dragonBones.FrameEvent):void {
        // egret.log( "Machine播放到了一个关键帧！ 帧标签为：",evt.frameLabel);
        /**机器状态控制 */
        switch(evt.frameLabel) {
            case "btn-go-press":
                this.status = Machine.STATUS.clutching;
                this.dollClutched = null;
                break;
            case "begin":
                this.status = Machine.STATUS.ready;
                break;
            case "clutch_back_before":
                if (this.dollClutched) {
                    let bone = this.armature.getBone("松鼠");
                    let slot = bone.getSlots()[0];
                    slot.displayIndex = 0
                    slot.display.texture = this.dollClutched.dollTexture;
                    bone.invalidUpdate()
                }
                break;
            case "clutch_back":
                if (this.dollClutched) {
                    let self = this;
                    let panel = new eui.Panel();
                    panel.horizontalCenter = 0;
                    panel.verticalCenter = 0;
                    panel.addEventListener(egret.Event.ADDED, function(){                        
                        this.goldCount.text = "×"+ self.dollClutched.gold;
                        this.confirmButton.addEventListener(egret.TouchEvent.TOUCH_TAP, this.close, this)
                    }, panel)
                    panel.addEventListener(egret.Event.REMOVED, function(){                        
                        let bone = self.armature.getBone("松鼠");
                        let slot = bone.getSlots()[0];
                        slot.displayIndex = -1;
                        self.status = Machine.STATUS.ready;
                    }, panel);
                    this.parent.addChild(panel);
                } else {
                    this.status = Machine.STATUS.ready;
                }
                break;
        }
        /**事件触发 */
        if (this.hasEventListener(evt.frameLabel)) {
            let nEvt = new egret.Event(evt.frameLabel)
            this.dispatchEvent(nEvt);
        }
    }
    /**抓到松鼠 */
    public clutched(doll:Doll):void {
        this.dollClutched = doll;
    }
    /**销毁机器 */
    public destory():void {
        if (this.parent) {
            this.parent.removeChild(this);
        }
        this.status = Machine.STATUS.disable;
        this.actionArray = null;
        this.armature = null;
        this.btnArmature = null;
        this.armatureDisplay = null;
        this.btnArmatureDisplay = null;
        this.removeEventListener(egret.Event.ENTER_FRAME, this.onEnterFrame, this);
        this.removeEventListener(dragonBones.FrameEvent.ANIMATION_FRAME_EVENT, this.onFrameEvent,this);
    }
}

/**
 * 松鼠
 */
class Doll extends egret.Sprite {
    /**金币模式:x5\x10\x20 */
    private goldModel:number;
    /**松鼠的id */
    public id:number;
    /**松鼠携带的金币 */
    public gold:number;
    /**dollTexture */
    public dollTexture;
    /**松鼠的状态标识 */
    public status;
    public constructor(goldModel:number) {
        super();
        this.name = "Doll";
        this.id = new Date().getTime();
        this.goldModel = goldModel;
        this.gold = this.goldModel*this.randomMultiple();
        this.create();
    }
    /**随机产生松鼠携带金币倍数 */
    private randomMultiple():number {
        let m = 1, per=Math.random()*100;
        if (per<=5) {
            m = 4;
        } else if (per<=20){
            m = 3;
        } else if (per<=50){
            m = 2;
        } else {
            m = 1;
        }
        return m;
    }

    /**松鼠的动作列表 */
    private actionArray;
    /**松鼠的实体数据 */
    private armature;
    /**松鼠的可视对象 */
    private armatureDisplay;
    /**创建松鼠骨骼模型 */
    private create():void {
        this.actionArray = ["go"];
        this.x = 0;
        this.y = 0;
        //读取松鼠的骨骼数据,并创建实例显示到舞台
        let skeletonData = RES.getRes("doll_ske_json");
        let textureData = RES.getRes("doll_tex_json");
        let texture = RES.getRes("doll_tex_png");
        let factory = new dragonBones.EgretFactory();
        factory.addSkeletonData(dragonBones.DataParser.parseDragonBonesData(skeletonData));
        factory.addTextureAtlas(new dragonBones.EgretTextureAtlas(texture, textureData));
        this.armature = factory.buildArmature("doll");
        this.armatureDisplay = this.armature.getDisplay();
        this.addChild(this.armatureDisplay);
        this.armatureDisplay.scaleX = 1; //设置X轴缩放比例
        this.armatureDisplay.scaleY = 1; //设置Y轴缩放比例
        this.armatureDisplay.x = 0;
        this.armatureDisplay.y = Math.random()*70;
        this.drawGold();

        this.addEventListener(egret.Event.ENTER_FRAME, this.onEnterFrame, this);
        dragonBones.WorldClock.clock.add(this.armature);

        /**绑定关键帧监听事件 */
        this.armature.addEventListener(dragonBones.FrameEvent.ANIMATION_FRAME_EVENT, this.onFrameEvent, this);
    }
    private drawGold():void {
        if (this.armatureDisplay) {
            let img = this.armatureDisplay.getChildAt(0);
            let tempDisplayObject = new egret.DisplayObjectContainer();
            let tempBitmap = new egret.Bitmap();
            tempBitmap.texture = img.texture;
            tempBitmap.width = img.width;
            tempBitmap.height = img.height;
            tempDisplayObject.addChild(tempBitmap);
            let tempTextField = new egret.TextField();
            tempTextField.text = ""+this.gold;
            tempTextField.textColor = 0x7e542a;
            tempTextField.textAlign = "center";
            tempTextField.bold = true;
            tempTextField.size = 30;
            tempTextField.width = 50;
            tempDisplayObject.addChild(tempTextField);
            tempTextField.x = 38;
            tempTextField.y = 130;
            //myGame.getMachine().getDollsContainer().addChild(tempDisplayObject);
            let renderTexture:egret.RenderTexture = new egret.RenderTexture();
            renderTexture.drawToTexture(tempDisplayObject);
            img.texture = renderTexture;
            this.dollTexture = renderTexture;
        }
    }
    /**动画播放 */
    private onEnterFrame(evt:egret.Event):void {
        dragonBones.WorldClock.clock.advanceTime(  -1 );
    }
    /**播放指定动作 */
    private play(action:string,...args:any[]):void {
        this.armature.animation.play(action, 1);
    }
    /**动画关键帧监听 */
    private onFrameEvent(evt:dragonBones.FrameEvent):void {
        if (evt.frameLabel == "go") {
            this.destory()
        }
        if (this.hasEventListener(evt.frameLabel)) {
            let nEvt = new egret.Event(evt.frameLabel)
            this.dispatchEvent(nEvt);
        }
    }
    /**松鼠开始移动 */
    public go():void {
        this.play("go");
    }
    /**销毁松鼠 */
    public destory():void {
        if (this.parent) {
            this.parent.removeChild(this);
        }
        this.status = null;
        this.actionArray = null;
        this.armature = null;
        this.armatureDisplay = null;
        this.removeEventListener(egret.Event.ENTER_FRAME, this.onEnterFrame, this);
        this.removeEventListener(dragonBones.FrameEvent.ANIMATION_FRAME_EVENT, this.onFrameEvent,this);
    }
}


